package com.cqgcxy.shopping.controller;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqgcxy.shopping.common.CommException;
import com.cqgcxy.shopping.domain.Administrator;
import com.cqgcxy.shopping.service.AdminService;

@WebServlet(urlPatterns="/administrator/adminlogin.do")
public class AdminLoginServlet extends HttpServlet{

	private static final long serialVersionUID = 8949573697890205043L;
	private Logger  logger = LoggerFactory.getLogger(getClass());
	private AdminService adminService=new AdminService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("1111");
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("login.dopost");
		try {
			// 1.抽取参数，封装为实体对象
			String admincode=req.getParameter("admincode");
			String adminpassword=req.getParameter("adminpassword");
			logger.debug("获取参数成功：{},{}",admincode,adminpassword);
			// 2.类型转换
			logger.debug("类型转换成功");
			// 3.数据校验
			//账号不为空
			if(admincode==null||admincode.trim().length()<=0) {
				throw new CommException("管理员账号不能为空");
			}
			//密码不能为空
			if(adminpassword==null||adminpassword.trim().length()<6) {
				throw new CommException("管理员密码长度错误");
			}
			/*if(kaptcha==null||kaptcha.trim().length()<0) {
				throw new CommException("验证码错误");
			}
			
			Object object=session.getAttribute("kaptcha"); //获取session中的验证码
			if(!kaptcha.equals(object)) {
				throw new CommException("验证码输入错误");
			}*/
			logger.debug("校验成功");
			//4.参数封装为对象
			Administrator administrator = new Administrator();
			administrator.setAdmincode(admincode);
			administrator.setAdminpassword(adminpassword);
			
			// 5.调用业务方法
			
			HttpSession session=req.getSession();
			session.setAttribute("administrator", administrator);
			logger.debug("业务处理成功");
			Administrator.adminlogin(admincode, adminpassword);
			// 6.转发或者重定向
			resp.sendRedirect(req.getContextPath()+"/admin/backstageindex.jsp");//重定向
			logger.debug("登陆成功");
			
		} catch (Exception e) {
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			logger.info("登录失败:{}",e.getMessage());
		}
	}	
	
}
